import { getCssVariableValue } from '@/utils/utils';

/** 表格相关 */
const tradeRoles = {
  1: { bg: 'rgba(48, 212, 133, 0.1)', name: '买入' },
  2: { bg: 'rgba(253, 79, 67, 0.1)', name: '卖出' },
};

const dataDic = {
  交易方向: 'tradeRole',
  成交电量: 'clearingQuantity',
  成交电价: 'clearingPrice',
  申报电量: 'declarationQuantity',
  申报电价: 'declarationPrice',
  市场均价: 'averageMarketPrice',
  收益: 'earnings',
};

const TABLE_HEAD = {
  tradeRole: {
    name: '交易方向',
    getCellProps: (v) => ({ style: { background: tradeRoles[v]?.bg || '' } }),
  },
  clearingQuantity: { name: '成交电量 (MWh)' },
  clearingPrice: { name: '成交电价 (元/MWh)' },
  declarationQuantity: { name: '申报电量 (MWh)' },
  declarationPrice: { name: '申报电价 (元/MWh)' },
  averageMarketPrice: { name: '市场均价 (元/MWh)' },
  earnings: { name: '收益' },
};
export const CODE1 = 'title'; // 首列自定义字段
export const getColumns = (codes) => [
  {
    code: CODE1,
    name: '聚合维度',
    width: '100%',
    align: 'left',
    lock: true,
  },
  ...codes.map((code) => ({
    ...TABLE_HEAD[code],
    code,
    width: 100,
    align: 'center',
  })),
];

/** 图相关 */
const CHART_MAP = {
  clearingQuantity: { type: 'bar', name: '成交电量', color: '#39507C' },
  declarationQuantity: { type: 'bar', name: '申报电量', color: '#44816A' },
  clearingPrice: { type: 'line', name: '成交电价', color: '#F5BE15', props: { yAxisIndex: 1 } },
  declarationPrice: { type: 'line', name: '申报电价', color: '#67DCAB', props: { yAxisIndex: 1 } },
  averageMarketPrice: {
    type: 'line',
    name: '市场均价',
    color: '#44816A',
    props: { yAxisIndex: 1 },
  },
  earnings: {
    type: 'bar',
    name: '收益',
    color: '#39507C',
  },
};

export const getNXChartOption = (codes) => {
  const dataset = { source: [], dimensions: [CODE1, ...codes] };
  const series = codes.map((code) => CHART_MAP[code]);
  return {
    dataset,
    series,
    grid: { top: 24, left: 48, bottom: 48, right: 48 },
    tooltip: {},
    legend: {
      textStyle: {
        color: getCssVariableValue('--chart-legend-color'),
      },
    },
    xAxis: [
      {
        type: 'category',
        axisLine: {
          lineStyle: {
            color: getCssVariableValue('--chart-x-line'),
          },
        },
        axisTick: {
          lineStyle: {
            color: getCssVariableValue('--chart-x-line'),
          },
        },
        axisLabel: {
          color: getCssVariableValue('--chart-font-color'),
        },
        axisPointer: {
          type: 'line',
          lineStyle: {
            color: getCssVariableValue('--chart-x-line'),
          },
        },
      },
    ],
    yAxis: [
      {
        type: 'value',
        name: '元',
        nameTextStyle: {
          color: getCssVariableValue('--chart-font-color'),
        },
        splitLine: {
          lineStyle: {
            color: getCssVariableValue('--chart-y-line'),
          },
        },
        axisLabel: {
          color: getCssVariableValue('--chart-font-color'),
        },
      },
      {
        type: 'value',
        name: '元/MWh',
        nameTextStyle: {
          color: getCssVariableValue('--chart-font-color'),
        },
        splitLine: {
          lineStyle: {
            color: getCssVariableValue('--chart-y-line'),
          },
        },
        axisLabel: {
          color: getCssVariableValue('--chart-font-color'),
        },
      },
    ],
  };
};
export const getChartOption = (codes) => {
  const dataset = { source: [], dimensions: [CODE1, ...codes] };
  const series = codes.map((code) => CHART_MAP[code]);
  return {
    dataset,
    series,
    grid: { top: 24, left: 48, bottom: 48, right: 48 },
    tooltip: {},
    legend: {
      textStyle: {
        color: getCssVariableValue('--chart-legend-color'),
      },
    },
    xAxis: [
      {
        type: 'category',
        axisLine: {
          lineStyle: {
            color: getCssVariableValue('--chart-x-line'),
          },
        },
        axisTick: {
          lineStyle: {
            color: getCssVariableValue('--chart-x-line'),
          },
        },
        axisLabel: {
          color: getCssVariableValue('--chart-font-color'),
        },
        axisPointer: {
          type: 'line',
          lineStyle: {
            color: getCssVariableValue('--chart-x-line'),
          },
        },
      },
    ],
    yAxis: [
      {
        type: 'value',
        name: 'MWh',
        nameTextStyle: {
          color: getCssVariableValue('--chart-font-color'),
        },
        splitLine: {
          lineStyle: {
            color: getCssVariableValue('--chart-y-line'),
          },
        },
        axisLabel: {
          color: getCssVariableValue('--chart-font-color'),
        },
      },
      {
        type: 'value',
        name: '元/MWh',
        nameTextStyle: {
          color: getCssVariableValue('--chart-font-color'),
        },
        splitLine: {
          lineStyle: {
            color: getCssVariableValue('--chart-y-line'),
          },
        },
        axisLabel: {
          color: getCssVariableValue('--chart-font-color'),
        },
      },
    ],
  };
};

// 交易类型
export const tradeOptions = () => [
  {
    label: '集中竞价',
    value: '集中',
    tradeType: [3],
    operators: {
      clearingIncome: 'sum',
      clearingPrice: 'clearingIncome / clearingQuantity',
      clearingQuantity: 'sum',
      declarationIncome: 'sum',
      declarationPrice: 'declarationIncome / declarationQuantity',
      declarationQuantity: 'sum',
      tradeRole: 'diff-append',
    },
    chartOptions: getChartOption([
      'clearingQuantity',
      'clearingPrice',
      'declarationQuantity',
      'declarationPrice',
    ]),
    tableColumns: getColumns([
      'tradeRole',
      'clearingQuantity',
      'clearingPrice',
      'declarationQuantity',
      'declarationPrice',
    ]),
  },
  {
    label: '滚动撮合',
    value: '滚动',
    tradeType: [1, 2, 4],
    operators: {
      clearingIncome: 'sum',
      clearingPrice: 'clearingIncome / clearingQuantity',
      clearingQuantity: 'sum',
      tradeRole: 'diff-append',
    },
    chartOptions: getChartOption(['clearingQuantity', 'clearingPrice']),
    tableColumns: getColumns(['tradeRole', 'clearingQuantity', 'clearingPrice']),
  },
];
// "marketClearIncome": "sum",
// "marketClearingQuantity": "sum",
// "marketClearingPrice": "marketClearIncome / marketClearingQuantity"

/**
 * 格式化数据
 * @param {*} _data 接口返回的数据
 * @param {array} _order 聚合维度
 * @returns
 */
export const getTableData = (_data, _order, marketId) => {
  const { data, head } = _data || {};
  if (!_data || !data || !head) return [];
  // 数据处理
  const fmtPoint = (v) => (v < 10 ? `0${v}00` : `${v}00`);
  const fmtDate = (v) => v.replace(/[-]/g, '');
  const fmtRow = (_row, _title, _tag) => {
    let res = {
      id: _.uniqueId(),
    };
    // 首列
    res[CODE1] = _tag === '时点' ? fmtPoint(_title) : _tag === '日期' ? fmtDate(_title) : _title;
    // 映射取值
    head.map((k, i) => {
      const code = dataDic?.[k];
      let val = _row?.[i];
      if (code === 'tradeRole') {
        // 交易方向
        val = val ? tradeRoles[Number(val)]?.name || '-' : '-';
      } else {
        // 保留小数
        const fixnum = code?.includes('Quantity') ? 3 : 2;
        val = parseFloat(val).toFixed(fixnum);
      }
      if (marketId === 'PXBNX') {
        if (_tag === '交易单元' && k === '交易方向') {
          res[code] = '-';
        } else if (_tag === '序列' && k === '交易方向') {
          res[code] = '-';
        } else if (_tag === '日期' && k === '交易方向') {
          res[code] = '-';
        } else if (!_tag && k === '交易方向') {
          res[code] = '-';
        } else if (_tag === '交易单元' && k === '市场均价') {
          res[code] = '-';
        } else if (_tag === '序列' && k === '市场均价') {
          res[code] = '-';
        } else if (_tag === '日期' && k === '市场均价') {
          res[code] = '-';
        } else if (!_tag && k === '市场均价') {
          res[code] = '-';
        } else {
          res[code] = val;
        }
      } else {
        res[code] = val;
      }
    });
    return res;
  };
  // 递归种一颗树
  let exportTable = []; // 导出用
  const fn = ({ total, ...list }, title, lv) => {
    let result = fmtRow(total, title, _order[lv - 1]);
    exportTable.push(result);
    let children = [];
    for (const k in list) {
      const temp = !!list[k]?.length ? fmtRow(list[k], k, _order[lv]) : fn(list[k], k, lv + 1);
      children.push(temp);
      exportTable.push(temp);
    }
    if (!!children.length) {
      result.children = children.sort((a, b) => a[CODE1].localeCompare(b[CODE1], 'zh-CN'));
    }
    return result;
  };
  // 总合计要单独一行
  const { children, ...total } = fn(data, '合计', 0);
  const tableData = [total, ...children];
  return { tableData, exportTable };
};
